import time

import execjs
import requests

from app.modules1.common.config import memberName
from app.modules1.common.toolss import md5_hash

memberName = "800901"


def getTokenInfo(userName, password):
    timestamp = int(time.time() * 1000)
    print("getTokenInfo", userName, password)
    userIdResult = getUserId(userName, memberName)
    if userIdResult["code"] != 200:
        return userIdResult
    userId = userIdResult["data"]
    print("===", userId)
    with open("./js/common.js", "r", encoding="utf-8") as file:
        js_code = file.read()
        # 创建JavaScript执行环境
    ctx = execjs.compile(js_code)
    two = ctx.call("SHA256", md5_hash(str(userId) + password)).upper()
    passwordSha256 = ctx.call("SHA256", two + str(timestamp)).upper()
    password_j = md5_hash(md5_hash(str(userId) + password) + str(timestamp))
    # 进行登录
    result = login(password_j, passwordSha256, userId, str(timestamp))

    return result


def login(password, passwordSha256, userId, timestamp):
    url = "https://web.jackyun.com/auth/v5/web/login"
    data = {
        "memberName": memberName,
        "userId": userId,
        "password": password,
        "passwordSha256": passwordSha256,
        "timestamp": timestamp,
        "nodeId": "_1SFK97ZSN_YOX5CGNTW",
        "clientSn": "RFWIM56G-SFLR-BROSWER",
        "ati": "1649220462358",
        "loginDevice": "web_browser",
        "app_key": "jackyun_web_browser_2024",
    }
    headers = {
        "authority": "web.jackyun.com",
        "method": "POST",
        "path": "/jkyun/erp-baseinfo/open/user/getbyuserid",
        "scheme": "https",
        "accept": "*/*",
        "clientId": "jackyun_web_browser_2024",
        "accept-encoding": "gzip, deflate, br, zstd",
        "accept-language": "zh-CN,zh;q=0.9",
        "ati": "3306050494034",
        "authorization": "Bearer 159D0A74E6AB77280179711C7A64FA54",
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "cookie": "_ati=3306050494034; 3AB9D23F7A4B3CSS=jdd03K7FISUQPYHH7JDSPJIUMRYIEQDMEMMWRLYAIHRD4XYD3YNG6NIQUUN7QI2FMCFWI2OCZWEZ65PADQHEEN3GZBZIUMIAAAAMVLR4VZRYAAAAACK3H56X4WQEDJMX; 3AB9D23F7A4B3C9B=K7FISUQPYHH7JDSPJIUMRYIEQDMEMMWRLYAIHRD4XYD3YNG6NIQUUN7QI2FMCFWI2OCZWEZ65PADQHEEN3GZBZIUMI; token=1A54F9308BF2DDD3D93369F8D94B93A0; group=g003; canaryFlag=null; canaries=null",
        "module_code": "mainframe",
        "origin": "https://web.jackyun.com",
        "priority": "u=1, i",
        "referer": "https://web.jackyun.com/home/mainframe_web.html",
        "sec-ch-ua": '"Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"',
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": '"Windows"',
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
        "x-requested-with": "XMLHttpRequest",
    }
    # 发送POST请求
    response = requests.post(
        url, headers=headers, proxies={"http": None, "https": None}, data=data
    )

    print("--", response.json())
    return response.json()


# 获取UserId
def getUserId(userName, memberName):
    # 请求URL
    url = (
            "https://web.jackyun.com/auth/getUserId?userName="
            + userName
            + "&memberName="
            + memberName
    )
    print(url)
    # 请求头
    headers = {
        "authority": "web.jackyun.com",
        "method": "POST",
        "path": "/jkyun/erp-baseinfo/open/user/getbyuserid",
        "scheme": "https",
        "accept": "*/*",
        "accept-encoding": "gzip, deflate, br, zstd",
        "accept-language": "zh-CN,zh;q=0.9",
        "ati": "3306050494034",
        "authorization": "Bearer 159D0A74E6AB77280179711C7A64FA54",
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "cookie": "_ati=3306050494034; 3AB9D23F7A4B3CSS=jdd03K7FISUQPYHH7JDSPJIUMRYIEQDMEMMWRLYAIHRD4XYD3YNG6NIQUUN7QI2FMCFWI2OCZWEZ65PADQHEEN3GZBZIUMIAAAAMVLR4VZRYAAAAACK3H56X4WQEDJMX; 3AB9D23F7A4B3C9B=K7FISUQPYHH7JDSPJIUMRYIEQDMEMMWRLYAIHRD4XYD3YNG6NIQUUN7QI2FMCFWI2OCZWEZ65PADQHEEN3GZBZIUMI; token=1A54F9308BF2DDD3D93369F8D94B93A0; group=g003; canaryFlag=null; canaries=null",
        "module_code": "mainframe",
        "origin": "https://web.jackyun.com",
        "priority": "u=1, i",
        "referer": "https://web.jackyun.com/home/mainframe_web.html",
        "sec-ch-ua": '"Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"',
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": '"Windows"',
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
        "x-requested-with": "XMLHttpRequest",
    }
    # 自己写的JS完成的
    data = {}

    # 发送POST请求
    response = requests.get(url, headers=headers, data=data)
    print("获取用户ID接口结果", response.json())
    result = response.json()
    if result["code"] == 0:
        return {"code": 0, "msg": "账号错误"}
    elif result["code"] == 200:
        return {"code": 200, "data": response.json()["result"]["data"]}
    else:
        return {"code": 0, "msg": "未知错误"}


def getRefreshToken(refreshToken):
    url = "https://web.jackyun.com/auth/refresh"
    headers = {
        "clientId": "jackyun_web_browser_2024",
    }
    data = {"refreshToken": refreshToken}
    # 发送POST请求
    response = requests.post(url, headers=headers, data=data)
    # 打印响应内容
    tokens = response.json()
    return {
        "access_token": tokens["access_token"],
        "refresh_token": tokens["refresh_token"],
    }


def getToken():
    url = "https://scrm.zuixiyu.com/flask/api/getRefreshToken"
    headers = {
        "clientId": "jackyun_web_browser_2024",
        "Content-Type": "application/json",
    }
    data = {}

    try:
        response = requests.post(url, headers=headers, json=data)
        response.raise_for_status()  # 检查请求是否成功
        result = response.json()
        print("获取Token结果:", result)
        return result
    except requests.exceptions.RequestException as e:
        print("请求失败:", e)
        return {"error": str(e)}
    except ValueError as e:
        print("解析JSON失败:", e)
        return {"error": "Invalid JSON response"}

